package com.dk.util.http.req;

import com.dk.enumerate.HttpEnum;
import com.google.common.base.Strings;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import java.io.File;

/**
 * 获取请求主体信息类
 */
public class GainReqBody {
    /**
     * 通过请求体类型获取请求体对象
     * @param bodyType 请求类型
     * @param body 请求体字符串
     * @return 请求体对象
     */
    public static RequestBody getReqBodyOnType(String bodyType, String body){
        RequestBody requestBody = null;
        if(!Strings.isNullOrEmpty(bodyType)){
            if(HttpEnum.JSON.getValue().equals(bodyType.toUpperCase())){
                //创建json请求体对象
                requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),body);
            }else if(HttpEnum.XML.getValue().equals(bodyType.toUpperCase())){
                //创建xml请求体对象
                requestBody = RequestBody.create(MediaType.parse("application/xml"),body);
            }else if(HttpEnum.FILE.getValue().equals(bodyType.toUpperCase())){
                //新建文件对象
                File file = new File(body);
                MultipartBody.Builder builder = new MultipartBody.Builder();
                builder.setType(MediaType.parse("multipart/form-data"));
                //添加文件
                builder.addFormDataPart(HttpEnum.FILE.getValue().toLowerCase(), file.getName(), RequestBody.create(file, null));
                //请求体完成构建
                requestBody = builder.build();
            }
        } else{
            //创建请求体对象
            requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),body);
        }
        return requestBody;
    }
}
